package com.xwj.controller.front;

import com.xwj.data.StaticData;
import com.xwj.dto.ForgetPwdDto;
import com.xwj.entity.PassWordEntity;
import com.xwj.entity.RaRegisterUser;
import com.xwj.service.Impl.RegisterUserServiceImpl;
import com.xwj.service.holder.RaRegisterUserHolder;
import com.xwj.util.ValidatedUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * Created by xuweijie on 2018/1/1.
 */
@RestController
@RequestMapping("/front/")
public class FrontLoginController {

    @Autowired
    private RegisterUserServiceImpl registerUserService;

    @RequestMapping("login/loginView")
    public ModelAndView loginView(ModelAndView modelAndView) {
        modelAndView.setViewName("front/login");
        return modelAndView;
    }

    /**
     * 登录
     *
     * @param passWordEntity
     * @param request
     * @return
     */
    @RequestMapping(value = "login/loginData", method = RequestMethod.POST)
    public Map<String, Object> loginData(PassWordEntity passWordEntity, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        Optional<RaRegisterUser> raRegisterUser;
        if (ValidatedUtils.checkCellphone(passWordEntity.getId()))
            raRegisterUser = Optional.ofNullable(registerUserService.findUserByPhone(passWordEntity.getId()));
        else if (ValidatedUtils.checkEmail(passWordEntity.getId()))
            raRegisterUser = Optional.ofNullable(registerUserService.findUserByMail(passWordEntity.getId()));
        else
            raRegisterUser = Optional.ofNullable(registerUserService.findUserById(passWordEntity.getId()));
        if (raRegisterUser.isPresent()) {
            if (RaRegisterUserHolder.checkPassWord(raRegisterUser.get().getId(), passWordEntity.getPassword())) {
                ServletContext context = request.getServletContext();
                if (StringUtils.isNotBlank((String) context.getAttribute(StaticData.REGISTER_USER_LOGIN_ATTRIBUTE)))
                    context.removeAttribute(StaticData.REGISTER_USER_LOGIN_ATTRIBUTE);
                context.setAttribute(StaticData.REGISTER_USER_LOGIN_ATTRIBUTE, raRegisterUser.get().getId());
                context.setAttribute(StaticData.REGISTER_USER_DATA, raRegisterUser.get());
                map.put("msg", "登陆成功");
            } else
                map.put("msg", "密码不正确");
        } else
            map.put("msg", "用户信息不存在");
        return map;
    }

    /**
     * 忘记密码
     *
     * @param forgetPwdDto
     * @return
     */
    @RequestMapping(value = "forgetPwd", method = RequestMethod.POST)
    public Map<String, Object> forgetPwd(ForgetPwdDto forgetPwdDto) {
        Map<String, Object> map = new HashMap<>();
        Optional<RaRegisterUser> raRegisterUser = Optional.ofNullable(registerUserService.findUserByPhone(forgetPwdDto.getPhone()));
        if (raRegisterUser.isPresent()) {
            if (!raRegisterUser.get().getIdCard().equals(forgetPwdDto.getIdCard())) {
                map.put("msg", "身份证验证不通过，请输入本人身份证号码");
                return map;
            }
        } else {
            map.put("msg", "无绑定该手机号码的用户，请输入正确手机号码");
            return map;
        }
        PassWordEntity passWordEntity = new PassWordEntity();
        passWordEntity.setId(raRegisterUser.get().getId());
        passWordEntity.setPassword(forgetPwdDto.getPassword());
        if (registerUserService.updatePassword(passWordEntity) > 0)
            map.put("msg", "密码已成功找回，请登录");
        else
            map.put("msg", "密码找回失败，请重试");
        return map;
    }

    /**
     * 退出
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "logout", method = RequestMethod.POST)
    public Map<String, Object> logout(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        ServletContext context = request.getServletContext();
        context.removeAttribute(StaticData.REGISTER_USER_LOGIN_ATTRIBUTE);
        map.put("msg", "已退出当前登录");
        return map;
    }

    @RequestMapping(value = "logout2")
    public void logout2(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ServletContext context = request.getServletContext();
        context.removeAttribute(StaticData.REGISTER_USER_LOGIN_ATTRIBUTE);
        response.sendRedirect("/front/index");
    }


}
